const Service = require('egg').Service;
const { initDomNode , insertNode , render , XMl_render } = require("../utils/common") 
const path = require("path");

class PageService extends Service {
  async page_save(arr,pid,view_name) {
    // const user = await this.ctx.db.query('select * from user where uid = ?', uid);
    // return user;
    for(let item of arr) {
        const tagRes = await this.app.mysql.query(`select * from magic_tag where tag='${item.tag}'`);
        const result = await this.app.mysql.insert('magic_page_view', { 
            magic_tag: tagRes[0].id,
            pid,
            magic_css:item.class,
            text:item.text,
            attr:item.attr,
            view_name,
            magic_style: item.style,
            magic_id:item.id,
        });
        if(item.children && item.children.length)
            await this.page_save(item.children,result.insertId,view_name)
    } 
    // "tag": "img",
    // "class": null,
    // "id": null,
    // "style": "",
    // "children": [],
    // "attr": "src=\"http://106.12.76.26:3560/static/image/Cbanner.jpeg\"",
    // "text": ""
  }
  // 获取页面 数据
  async get_page_detail(pageName){

    const { ctx } = this;
    console.log(ctx.headers.host)
    // try{
      // 页面路由 
      // magic_tag
      const results = await this.app.mysql.query(`select a.*,b.tag,b.type as tag_type from 
        (
          select a.pageTitle,a.javaScriptOption,b.* from magic_page as a 
          LEFT JOIN magic_page_view as b 
          on a.pageName = b.view_name
          where a.pageName = '${pageName}'
        ) as a
        LEFT JOIN magic_tag as b
        on a.magic_tag = b.id ORDER BY a.id asc`);
      const { pageTitle,javaScriptOption } = results[0]
      const nodes = initDomNode(results);
      for(let item of nodes){
        if(item.magic_page_components_name){
          const components_results = await this.app.mysql.query(`
            select a.*,b.tag,b.type as tag_type from magic_page_components as a
              LEFT JOIN magic_tag as b
              on a.magic_tag = b.id
              where a.component_name = '${item.magic_page_components_name}'`);
          const components_node = initDomNode(components_results);
          item.children = insertNode(item.children,components_node)
        }
      }
      let rdr = render
      if(ctx.headers.referer) rdr = XMl_render
      const { html , css_file } = rdr(nodes,{ pageTitle })
      
      // console.log(path.join(__dirname, `../public/temp/css/${pageName}.css`))
      // //写入内容
      // console.log(ctx.headers)
      let h = `<style>${css_file}</style>` + html;
      let script = ""
      if(javaScriptOption){
        script = `
          window.executeOption = ${javaScriptOption};
          for(var key in executeOption){
            if(key == 'swiper'){
              executeOption[key].map(item=>{
                item.fn = new swiper(item)
              })
            }
          }
        `
        if(!ctx.headers.referer){
          let lib = ""
          for( var key in JSON.parse(javaScriptOption) ){
            // 需要swiper 插件
            if(key == 'swiper'){
              lib += "<script src='http://106.12.76.26:3560/static/common/swiper.js' ></script>" 
            }
          }
          script = `${lib}<script  >${script}</script>`
        }

        // fs.writeFile(path.join(__dirname, `../public/temp/js/${pageName}.js`),`window.executeOption = ${javaScriptOption}; console.log(executeOption)`,function(error){
        //   console.log(error);
        // })
      }
      // referer 
      if(ctx.headers.referer){
        const attr = await this.app.mysql.query(`select magic_css,magic_id from magic_page_view where view_name = '${pageName}'  and  magic_css  <> '' or  magic_id  <> ''`);
        // ajax 请求
        return { h , script ,attr ,nodes };
      }else{
        // 正常请求
        return h + script ;
      }
  }

}

module.exports = PageService;